import { ElMessage } from 'element-plus';
import * as XLSX from 'xlsx';
// import XLSXS from 'xlsx-style';
import XLSXS from 'xlsx-js-style';
import { LevelDataValid } from '../interface'
export const reportExportExcel = (
	ReportDefData: Record<string, any>,
	mainGrpFieldCfg: Record<string, any>[],
	levelDataValidArray: LevelDataValid[],
	tableData: Record<string, any>,
	levelNumber: number,
	otherFields: Record<string, any>[]
) => {
	// 导出
	const handlerExportExcelBtn = () => {
		let wb: XLSX.WorkSheet = XLSX.utils.table_to_sheet(document.querySelector('#mytable')); // mytable为表格的id名

		if (!wb['!merges']) {
			ElMessage.warning('无法导出：报表无数据');
			return;
		}
		// wb['!cols'] = [{ wpx: 330 }, { wpx: 330 }, { wpx: 330 }, { wpx: 330 }];
		console.log('wb', { ...wb });
		// 样式的文档地址
		// https://www.npmjs.com/package/xlsx-style
		for (const key in wb) {
			// if (key.indexOf('!') === -1 && wb[key].v) {
			if (key.indexOf('!') === -1) {
				// console.log(wb[key], key, 'key')
				wb[key].s = {
					font: {
						// 字体设置
						sz: 13,
						bold: false,
						color: {
							rgb: '000000', // 十六进制，不带#
						},
					},
					alignment: {
						// 文字居中
						horizontal: 'center',
						vertical: 'center',
						wrap_text: true,
					},
					border: {
						// 设置边框
						top: { style: 'thin' },
						bottom: { style: 'thin' },
						left: { style: 'thin' },
						right: { style: 'thin' },
					},
				};
				if (wb[key].v === '') {
					wb[key].v = 0;
					wb[key].t = 'n';
				}
			}
		}
		const data = addRangeBorder(wb['!merges'], wb); // 合并项添加边框
		console.log('data', data);
		const filedata = sheet2blob(data);
		console.log('filedata', filedata);
		openDownloadDialog(filedata, ReportDefData?.PageName + '.xlsx');
	};

	const addRangeBorder = (range: XLSX.Range[], ws: XLSX.WorkSheet) => {
		const arr = [
			'A',
			'B',
			'C',
			'D',
			'E',
			'F',
			'G',
			'H',
			'I',
			'J',
			'K',
			'L',
			'M',
			'N',
			'O',
			'P',
			'Q',
			'R',
			'S',
			'T',
			'U',
			'V',
			'W',
			'X',
			'Y',
			'Z',
			'AA',
			'AB',
			'AC',
			'AD',
			'AE',
			'AF',
			'AG',
			'AH',
			'AI',
			'AJ',
			'AK',
			'AL',
			'AM',
			'AN',
			'AO',
			'AP',
			'AQ',
			'AR',
			'AS',
			'AT',
			'AU',
			'AV',
			'AW',
			'AX',
			'AY',
			'AZ',
			'BA',
			'BB',
			'BC',
			'BD',
			'BE',
			'BF',
			'BG',
			'BH',
			'BI',
			'BJ',
			'BK',
			'BL',
			'BM',
			'BN',
			'BO',
			'BP',
			'BQ',
			'BR',
			'BS',
			'BT',
			'BU',
			'BV',
			'BW',
			'BX',
			'BY',
			'BZ',
			'CA',
			'CB',
			'CC',
			'CD',
			'CE',
			'CF',
			'CG',
			'CH',
			'CI',
			'CJ',
			'CK',
			'CL',
			'CM',
			'CN',
			'CO',
			'CP',
			'CQ',
			'CR',
			'CS',
			'CT',
			'CU',
			'CV',
			'CW',
			'CX',
			'CY',
			'CZ',
			'DA',
			'DB',
			'DC',
			'DD',
			'DE',
			'DF',
			'DG',
			'DH',
			'DI',
			'DJ',
			'DK',
			'DL',
			'DM',
			'DN',
			'DO',
			'DP',
			'DQ',
			'DR',
			'DS',
			'DT',
			'DU',
			'DV',
			'DW',
			'DX',
			'DY',
			'DZ',
		];
		let str = ws['!ref']!.split(':')[1];
		str.replace(/\"/g, '');

		let nums = 0;

		let iCols = mainGrpFieldCfg.length + otherFields.length + 1;
		if (levelDataValidArray && mainGrpFieldCfg.length > 0) {
			iCols += levelDataValidArray.length;
			for (var j = 0; j < levelDataValidArray.length; j++) {
				// console.log(tmpLevelDataValidArray[j].childDataValid === [], '=====');
				var k_arr = levelDataValidArray[j].Childs;
				if (k_arr && k_arr.length) {
					iCols += k_arr.length - 1;
					for (var k = 0; k < k_arr.length; k++) {
						if (k_arr[k].FieldLevelName) {
							console.log('=====有三级');
							nums = 3;
						}
						if (k_arr[k].Childs && k_arr[k].Childs.length > 0) {
							iCols += k_arr[k].Childs.length - 1;
						}
						//  else {
						//   console.log('=====有二级')
						//   nums = 4
						// }
					}
				}
				if (k_arr === undefined || k_arr === null || k_arr.length === 0) {
					nums = 2;
				}
			}
		}
		// console.log('!ref', iCols, levelNumber, tableData.data.length);
		ws['!ref'] = 'A1:' + arr[iCols - 1] + Number(tableData.data.length + levelNumber + 1); // 加1是因为有个列合计
		range.forEach((item, index) => {
			if (item.e.r >= tableData.data.length + nums) {
				console.log(index, 'index');
				range.splice(index);
				// delete item
			}
			// s 为起始，r为行 ,c为列, e为结束列
			const startColNumber = Number(item.s.r);
			const endColNumber = Number(item.e.r);
			const startRowNumber = Number(item.s.c);
			const endRowNumber = Number(item.e.c);
			const test = ws[arr[startRowNumber] + (startColNumber + 1)];
			console.log(test, 'test');
			for (let col = startColNumber; col <= endColNumber; col++) {
				for (let row = startRowNumber; row <= endRowNumber; row++) {
					// console.log(arr[row], col, 'arr')
					ws[arr[row] + (col + 1)] = test;
					// ws['A8'] = {}
				}
			}
		});
		return ws;
	};
	// 将一个sheet转成最终的excel文件的blob对象，然后利用URL.createObjectURL下载
	const sheet2blob = (sheet: XLSX.WorkSheet, sheetName?: string) => {
		sheetName = sheetName || 'sheet1';
		var workbook = {
			SheetNames: [sheetName],
			Sheets: {},
		};
		workbook.Sheets[sheetName] = sheet; // 生成excel的配置项

		var wopts = {
			bookType: 'xlsx', // 要生成的文件类型
			bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
			type: 'binary',
		};
		var wbout = XLSXS.write(workbook, wopts);
		var blob = new Blob([s2ab(wbout)], {
			type: 'application/octet-stream',
		}); // 字符串转ArrayBuffer
		function s2ab(s) {
			var buf = new ArrayBuffer(s.length);
			var view = new Uint8Array(buf);
			for (var i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
			return buf;
		}
		return blob;
	};

	const openDownloadDialog = (url: any, saveName: string) => {
		if (typeof url === 'object' && url instanceof Blob) {
			url = URL.createObjectURL(url); // 创建blob地址
		}
		var aLink = document.createElement('a');
		aLink.href = url;
		aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
		var event;
		if (window.MouseEvent) event = new MouseEvent('click');
		else {
			event = document.createEvent('MouseEvents');
			event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
		}
		aLink.dispatchEvent(event);
	};
	return {
		handlerExportExcelBtn,
	};
};
